﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;

using EHTWebsite.Code;
using EHTWebsiteProject.Code.BLL;
using System.Resources;
using System.Threading;
using System.Globalization;
using System.Text;
using Telerik.Web.UI;

namespace EHTWebsiteProject.Administrator
{
    public partial class EHTPhanQuyen : System.Web.UI.Page
    {
        public Boolean IsVN = true;
        private String languageCode = "vi-VN";
        private ResourceManager rm = new ResourceManager("Resources.SiteMap", System.Reflection.Assembly.Load("App_GlobalResources"));    

        protected void Page_Load(object sender, EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(EHTPhanQuyen));
            if (!Page.IsPostBack)
            {
                try
                {
                    languageCode = Session[HangSo.LANGUAGE_CODE].ToString();
                    if (languageCode == "en-us")
                    {
                        IsVN = false;
                    }

                }
                catch (Exception ex)
                {
                }
                Thread.CurrentThread.CurrentCulture = new CultureInfo(languageCode);
                LoadLanguage(Thread.CurrentThread.CurrentCulture);
                LoadRoleUser();
                if (IsVN == true)
                {
                    plHeThong.GroupingText = HangSo.ListMenu;
                    plHome.GroupingText = HangSo.ListMenuHome;
                }
                else
                {
                    plHeThong.GroupingText = HangSo.ListMenuOther;
                    plHome.GroupingText = HangSo.ListMenuHomeOther;
                }

            }
        }

        /// <summary>
        /// Ham load ngon ngu
        /// </summary>
        /// <param name="ci"></param>
        public void LoadLanguage(CultureInfo ci)
        {
            lbSave.Text = rm.GetString("lbSave", ci);
            lbCancel.Text = rm.GetString("lbCancel", ci);
            lbApply.Text = rm.GetString("lbApply", ci);
            lbHelp.Text = rm.GetString("lbHelp", ci);
            lbAccount.Text = rm.GetString("lbAccount", ci);
            lbPhanQuyen.Text = rm.GetString("lbPhanQuyen",ci);

        }

        /// <summary>
        /// Ham load quyen User
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void LoadRoleUser()
        {
            DataSet ds = null;
            DataSet dsHome = null;
            String UserID = Request.QueryString["UserID"].ToString();
            if (UserID != "")
            {
                ds = DanhMucMenusProvider.GetMenusByUserId(UserID, 1);
                dsHome = DanhMucMenusProvider.GetMenusByUserId(UserID, 4);
            }
            else
            {
                ds = DanhMucMenusProvider.GetMenusByUserId("", 1);
                dsHome = DanhMucMenusProvider.GetMenusByUserId("", 4);
            }
            DataTable dtGroups = ds.Tables[0];
            DataTable dtUsers = ds.Tables[1];
            DataTable dtUserRights = ds.Tables[2];

            DataTable dtGroupsHome = dsHome.Tables[0];
            DataTable dtUsersHome = dsHome.Tables[1];
            DataTable dtUserRightsHome = dsHome.Tables[2];
            //Load user
            cboUsers.Items.Add(new RadComboBoxItem("", "000"));

            foreach (DataRow dr in dtUsers.Rows)
            {
                cboUsers.Items.Add(new RadComboBoxItem(dr["UserName"].ToString() + "(" + dr["UserID"].ToString() + ")", dr["UserID"].ToString()));
            }
            if (UserID != "")
                cboUsers.SelectedValue = UserID;
            else
                cboUsers.SelectedValue = "000";
            // Load menu items he thong
            trvMenus.CheckBoxes = true;
            Telerik.Web.UI.RadTreeNode oNode = new Telerik.Web.UI.RadTreeNode("EHT Menu", "0");
            oNode.ImageUrl = "../images/classic16.png";
            oNode.ExpandedImageUrl = "../images/folderopen.png";
            oNode.Style["cursor"] = "pointer";
            oNode.Expanded = true;
            //Load Treewiew
            BindTree("0", dtGroups, dtUserRights, oNode);
            trvMenus.Nodes.Add(oNode);

            ///menu trang home

            trvMenusHome.CheckBoxes = true;
            Telerik.Web.UI.RadTreeNode oNodeHOme = new Telerik.Web.UI.RadTreeNode("EHT Menu", "0");
            oNodeHOme.ImageUrl = "../images/classic16.png";
            oNodeHOme.ExpandedImageUrl = "../images/folderopen.png";
            oNodeHOme.Style["cursor"] = "pointer";
            oNodeHOme.Expanded = true;
            //Load Treewiew
            BindTreeHome("0", dtGroupsHome, dtUserRightsHome, oNodeHOme);
            trvMenusHome.Nodes.Add(oNodeHOme);
        }
        /// <summary>
        /// Find du lieu vao tree
        /// </summary>
        /// <param name="psGroupID"></param>
        /// <param name="pdtGroups"></param>
        /// <param name="pdtUserRights"></param>
        /// <param name="poNode"></param>
        private void BindTree(string psGroupID, DataTable pdtGroups, DataTable pdtUserRights, Telerik.Web.UI.RadTreeNode poNode)
        {
            foreach (DataRow dr in pdtGroups.Select("ParentID = '" + psGroupID + "'"))
            {
                RadTreeNode oNode;
                if(IsVN==true)
                    oNode = new Telerik.Web.UI.RadTreeNode(dr["MenuNameVN"].ToString() , dr["MenuID"].ToString());
                else
                    oNode = new Telerik.Web.UI.RadTreeNode(dr["MenuNameOther"].ToString(), dr["MenuID"].ToString());

                oNode.ImageUrl = "../images/classic16.png";
                oNode.ExpandedImageUrl = "../images/folderopen.png";
                oNode.Style["cursor"] = "pointer";

                if (IsVN == true)
                    oNode.ToolTip = dr["MenuNameVN"].ToString();
                else
                    oNode.ToolTip = dr["MenuNameOther"].ToString();
                

                oNode.Expanded = true;
                oNode.Checked = false;
                if (pdtUserRights.Select("MenuID='" + dr["MenuID"].ToString() + "'").Length > 0)
                    oNode.Checked = true;
                poNode.Nodes.Add(oNode);
                BindTree(dr["MenuID"].ToString(), pdtGroups, pdtUserRights, oNode);
            }
        }



        /// <summary>
        /// Find du lieu vao Tree home
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BindTreeHome(string psGroupID, DataTable pdtGroups, DataTable pdtUserRights, Telerik.Web.UI.RadTreeNode poNode)
        {
            foreach (DataRow dr in pdtGroups.Select("ParentID = '" + psGroupID + "'"))
            {
                RadTreeNode oNode;
                if (IsVN == true)
                    oNode = new Telerik.Web.UI.RadTreeNode(dr["MenuNameVN"].ToString(), dr["MenuID"].ToString());
                else
                    oNode = new Telerik.Web.UI.RadTreeNode(dr["MenuNameOther"].ToString(), dr["MenuID"].ToString());

                oNode.ImageUrl = "../images/classic16.png";
                oNode.ExpandedImageUrl = "../images/folderopen.png";
                oNode.Style["cursor"] = "pointer";

                if (IsVN == true)
                    oNode.ToolTip = dr["MenuNameVN"].ToString();
                else
                    oNode.ToolTip = dr["MenuNameOther"].ToString();


                oNode.Expanded = true;
                oNode.Checked = false;
                if (pdtUserRights.Select("MenuID='" + dr["MenuID"].ToString() + "'").Length > 0)
                    oNode.Checked = true;
                poNode.Nodes.Add(oNode);
                BindTreeHome(dr["MenuID"].ToString(), pdtGroups, pdtUserRights, oNode);
            }
        }


        protected void ImgSave_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                //Build Right table from treeview
                DataTable dtRights = new DataTable("");
                dtRights.Columns.Add("UserID");
                dtRights.Columns.Add("MenuID");
                // Build Lever 2
                foreach (RadTreeNode oNode1 in trvMenus.Nodes[0].Nodes)
                {
                    if (oNode1.Checked)
                    {
                        // Level 1
                        DataRow dr1 = dtRights.NewRow();
                        dr1["UserID"] = Request.QueryString["UserID"].ToString();
                        dr1["MenuID"] = oNode1.Value;
                        dtRights.Rows.Add(dr1);
                        foreach (RadTreeNode oNode2 in oNode1.Nodes)
                        {
                            // Level 2
                            if (oNode2.Checked)
                            {
                                DataRow dr2 = dtRights.NewRow();
                                dr2["UserID"] = Request.QueryString["UserID"].ToString();
                                dr2["MenuID"] = oNode2.Value;
                                dtRights.Rows.Add(dr2);
                            }
                        }
                    }
                }                             
               
                // Build Lever 2
                foreach (RadTreeNode oNodeHome1 in trvMenusHome.Nodes[0].Nodes)
                {
                    if (oNodeHome1.Checked)
                    {
                        // Level 1
                        DataRow dr1 = dtRights.NewRow();
                        dr1["UserID"] = Request.QueryString["UserID"].ToString();
                        dr1["MenuID"] = oNodeHome1.Value;
                        dtRights.Rows.Add(dr1);
                        foreach (RadTreeNode oNodeHome2 in oNodeHome1.Nodes)
                        {
                            // Level 2
                            if (oNodeHome2.Checked)
                            {
                                DataRow dr2 = dtRights.NewRow();
                                dr2["UserID"] = Request.QueryString["UserID"].ToString();
                                dr2["MenuID"] = oNodeHome2.Value;
                                dtRights.Rows.Add(dr2);
                            }
                        }
                    }
                }

                dtRights.AcceptChanges();

                SaveUserRights(dtRights);



                Response.Redirect("EHTUser.aspx");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void ImgApply_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                //Build Right table from treeview
                DataTable dtRights = new DataTable("");
                dtRights.Columns.Add("UserID");
                dtRights.Columns.Add("MenuID");
                // Build Lever 2
                foreach (RadTreeNode oNode1 in trvMenus.Nodes[0].Nodes)
                {
                    if (oNode1.Checked)
                    {
                        // Level 1
                        DataRow dr1 = dtRights.NewRow();
                        dr1["UserID"] = Request.QueryString["UserID"].ToString();
                        dr1["MenuID"] = oNode1.Value;
                        dtRights.Rows.Add(dr1);
                        foreach (RadTreeNode oNode2 in oNode1.Nodes)
                        {
                            // Level 2
                            if (oNode2.Checked)
                            {
                                DataRow dr2 = dtRights.NewRow();
                                dr2["UserID"] = Request.QueryString["UserID"].ToString();
                                dr2["MenuID"] = oNode2.Value;
                                dtRights.Rows.Add(dr2);
                            }
                        }
                    }
                }

                // Build Lever 2
                foreach (RadTreeNode oNodeHome1 in trvMenusHome.Nodes[0].Nodes)
                {
                    if (oNodeHome1.Checked)
                    {
                        // Level 1
                        DataRow dr1 = dtRights.NewRow();
                        dr1["UserID"] = Request.QueryString["UserID"].ToString();
                        dr1["MenuID"] = oNodeHome1.Value;
                        dtRights.Rows.Add(dr1);
                        foreach (RadTreeNode oNodeHome2 in oNodeHome1.Nodes)
                        {
                            // Level 2
                            if (oNodeHome2.Checked)
                            {
                                DataRow dr2 = dtRights.NewRow();
                                dr2["UserID"] = Request.QueryString["UserID"].ToString();
                                dr2["MenuID"] = oNodeHome2.Value;
                                dtRights.Rows.Add(dr2);
                            }
                        }
                    }
                }

                dtRights.AcceptChanges();

                SaveUserRights(dtRights);
                Response.Redirect("EHTPhanQuyen.aspx?UserID=" + cboUsers.SelectedValue);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void cboUsers_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string str = cboUsers.SelectedValue;
            Response.Redirect("EHTPhanQuyen.aspx?UserID=" + cboUsers.SelectedValue);
        }

        public static void SaveUserRights(DataTable pdtData)
        {
            try
            {
                if (pdtData.Rows.Count > 0)
                {
                    DanhMucMenusProvider.SaveUserRights(pdtData.Rows[0]["UserID"].ToString(), -1);
                    // Update new rights
                    foreach (DataRow dr in pdtData.Rows)
                    {
                        DanhMucMenusProvider.SaveUserRights(pdtData.Rows[0]["UserID"].ToString(), Int32.Parse(dr["MenuID"].ToString()));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        
    }
}